package com.vdongchina.thread.base.demo.threadpoolweb;


import com.vdongchina.thread.base.demo.threadpool.DefaultThreadPool;
import com.vdongchina.thread.base.demo.threadpool.Job;
import com.vdongchina.thread.base.demo.threadpool.ThreadPool;
import sun.net.www.content.image.png;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 简单模仿http浏览器请求线程池web
 */
public class SimpleHtttpServer {


    static ThreadPool<HttpRequestHandler> threadPool = new DefaultThreadPool<>(11);

    static String basePath;

    static ServerSocket serverSocket;

    static int port = 8080;

    public static void setPort(int port) {
        SimpleHtttpServer.port = port;
    }

    public static void setBasePath(String basePath) {
        if (basePath != null && new File(basePath).exists() && new File(basePath).isDirectory()) {
            SimpleHtttpServer.basePath = basePath;
            System.out.println(basePath);
        }
    }

    public static void start() throws IOException {
        serverSocket = new ServerSocket(port);
        Socket socket = null;

        while ((socket = serverSocket.accept()) != null) {
            System.out.println("请求");
            // 接收一个客户端Socket，生成一个HttpRequestHandler，放入线程池执行
            threadPool.execute(new HttpRequestHandler(socket));
        }
        serverSocket.close();
    }


    public static void main(String[] args) throws IOException {
        SimpleHtttpServer.setBasePath("/Users/yiyongyao/mydemo/demo-artConcurrent-thread/src/main/resrouces");
        SimpleHtttpServer.start();
    }


    public static class HttpRequestHandler implements Job {

        private Socket socket;

        public HttpRequestHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {

            String line = null;
            BufferedReader br = null;
            BufferedReader reader = null;
            PrintWriter out = null;
            InputStream in = null;
            try {
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String header = reader.readLine();
                String filePath = basePath +"/"+"2.png";
                out = new PrintWriter(socket.getOutputStream());
                if (filePath.endsWith("png") || filePath.endsWith("ico")) {
                    in = new FileInputStream(filePath);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int i = 0;
                    while ((i = in.read()) != -1) {
                        baos.write(i);
                    }
                    byte[] array = baos.toByteArray();
                    out.println("HTTP/1.1 200 ok");
                    out.println("Server: Molly");
                    out.println("Content-Type:image/jpeg");
                    out.println("Content-Length:" + array.length);
                    out.println("");
                    socket.getOutputStream().write(array, 0, array.length);
                } else {
                    br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
                    out = new PrintWriter(socket.getOutputStream());
                    out.println("HTTP/1.1 200 ok");
                    out.println("Server: Molly");
                    out.println("Content-Type: text/html; charset=UTF-8");
                    out.println("");
                    while ((line = br.readLine()) != null) {
                        out.print(line);
                    }
                }
                out.flush();
            } catch (Exception e) {
                out.println("HTTP/1.1 500");
                out.println("");
                out.flush();
            } finally {
                close(br, in, reader, out, socket);
            }
        }
    }


    private static void close(Closeable... closeables) {
        if (closeables != null) {
            for (Closeable closeable : closeables) {
                try {
                    if (null != closeable) {
                        closeable.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
